/**
 * 
 */
package com.fresh.api;

import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fresh.common.annotation.IgnoreAuth;
import com.fresh.dao.VerifyDao;
import com.fresh.entity.AntifraudUser;
import com.fresh.entity.GsCityEntity;
import com.fresh.entity.GsCode;
import com.fresh.entity.GsCreateEntity;
import com.fresh.entity.GsDistrict;
import com.fresh.entity.GsFactorEntity;
import com.fresh.entity.GsLoginResult;
import com.fresh.entity.GsRequest;
import com.fresh.entity.GsResultEntity;
import com.fresh.entity.SHE_BAOCodeEntity;
import com.fresh.entity.SHE_BAOResultEntity;
import com.fresh.entity.ZxExternalData;
import com.fresh.entity.ZxExternalSource;
import com.fresh.service.VerifyService;
import com.fresh.utils.Base64Utils;
import com.fresh.utils.HttpRequest;
import com.fresh.utils.HttpUtils;
import com.fresh.utils.PropertiesUtils;
import com.fresh.utils.Sequence;
import com.google.gson.Gson;

/**
 * 社保公积金接口调用
 * 
 * @author 公积金社保接口调用
 * @version 1.0
 * @date 2017年10月26日下午5:40:14 福乐康 Copyright© All Reserved 官方网站：www.flksh.com
 *       未经授权不得进行修改、复制、出售及商业使用
 */
@RequestMapping({ "/gjj" })
@Controller
public class GjjSheBaoController {

	private static final Logger log = LoggerFactory
			.getLogger(GjjSheBaoController.class);

	@Autowired
	private VerifyService verifyService;
	
	@Autowired
	private VerifyDao verifyDao;

	@IgnoreAuth
	@RequestMapping({ "toGjj" })
	public String toGs(HttpServletRequest request, AntifraudUser user)
			throws Exception {
		Gson gson=new Gson();
		request.setAttribute("id", user.getId());
		
		log.info("#toGs() 进入社保公积金查询页！");
		return "/buyer/GjjSheType";
	}
	
	
	@ResponseBody
	@IgnoreAuth
	@RequestMapping({ "getCitys" })
	public List<GsDistrict> getCitys(HttpServletRequest request, AntifraudUser user,
			String type) throws Exception {
		log.info("#getCitys() 开始查询城市列表！");
		
		try {
		Gson gson = new Gson();
		// 公积金是GJJ,社保是SHE_BAO;
		String gs_url = PropertiesUtils.getProperty("ssmh_url");
		String partner_code = PropertiesUtils.getProperty("partner_code");
		String partner_key = PropertiesUtils.getProperty("partner_key");

		String gs_city_url = gs_url + "task.unify.channel/v3?partner_code="+ partner_code + "&partner_key=" + partner_key+ "&channel_type=" + type + "&channel_status=0";
		String resCityJson = HttpUtils.doPostx(gs_city_url, null, null, 3, 10,"utf-8");

		if (StringUtils.isNotBlank(resCityJson)) {
			GsCityEntity gsCityEntity = gson.fromJson(resCityJson,GsCityEntity.class);
			log.info("#getCitys() 城市列表查询结果："+gson.toJson(gsCityEntity.getData().getList()));
			return gsCityEntity.getData().getList();
		}
		} catch (Exception e) {
		}
		return null;
	}

	@IgnoreAuth
	@RequestMapping(value = "getGs", produces = "application/json;charset=utf-8")
	public String getGs(HttpServletRequest request, GsRequest gsRequest,HttpServletResponse response)
			throws Exception {
		log.info("#getGs() 开始查询社保公积金信息！");
		
		try {
		Gson gson = new Gson();
		ZxExternalData zxExternalData=null;
		if (request.getSession().getAttribute("USER_SCORE")!=null) {
			 zxExternalData=(ZxExternalData) request.getSession().getAttribute("USER_SCORE");
			
			log.info("#getGs() 当前用户:" + gson.toJson(zxExternalData));
		}else{
			 PrintWriter out = response.getWriter();  
		        out.println("<html>");      
		        out.println("<script>");      
		        out.println("window.open ('"+request.getContextPath()+"/index','_top')");      
		        out.println("</script>");      
		        out.println("</html>");    
			return null;
		}
		
		gsRequest.setCode(gsRequest.getCity());
		String gs_url = PropertiesUtils.getProperty("ssmh_url");
		String partner_code = PropertiesUtils.getProperty("partner_code");
		String partner_key = PropertiesUtils.getProperty("partner_key");

		// 调用查询登录要素接口
		String gs_factor_url = gs_url + "task.unify.field/v3?partner_code="+ partner_code + "&partner_key=" + partner_key+ "&channel_type=" + gsRequest.getType() + "&channel_code="+ gsRequest.getCode();
		String resFactorJson = HttpUtils.doPostx(gs_factor_url, null, null, 3,10, "utf-8");
		log.info("#getGs() 调用查询登录要素接口:" + resFactorJson);
		GsFactorEntity gsFactorEntity = gson.fromJson(resFactorJson,GsFactorEntity.class);
		if (!gsFactorEntity.getCode().equals("2005")) {
			  request.setAttribute("message", "登录要素请求失败！");
			  return "/buyer/GJJResult";
		}

		// 调用创建任务接口
		String resCreateJson = null;
		String chsi_credit_url = gs_url + "task.unify.create/v3";
		Map<String, String> data = new HashMap<String, String>();
		data.put("partner_code", partner_code);
		data.put("partner_key", partner_key);
		data.put("channel_type", gsRequest.getType());
		data.put("channel_code", gsRequest.getCode());
		data.put("real_name", gsRequest.getRealName());
		data.put("identity_code", gsRequest.getIdentityCode());
		data.put("user_mobile", gsRequest.getUserMobile());
		HttpRequest httpRequest = HttpRequest.post(chsi_credit_url).form(data);
		if (httpRequest.ok()) {
			resCreateJson = httpRequest.body();
			log.info("#getGs() 调用创建任务接口返回信息：{}" + resCreateJson);
		}
		GsCreateEntity gsCreateEntity = gson.fromJson(resCreateJson,GsCreateEntity.class);

		// 调用登录验证接口：
//		Thread.sleep(3000);
		String gs_login_url = gs_url + "wxyj.unify.acquire/v3?partner_code="+ partner_code + "&partner_key=" + partner_key + "&task_id="+ gsCreateEntity.getTask_id()+ "&task_stage=INIT&request_type=submit&login_type="+ gsFactorEntity.getData().get(0).getValue() + "&user_name="+ gsRequest.getUserName() + "&user_pass="+ gsRequest.getUserPass();
		String resLoginJson = HttpUtils.doPostx(gs_login_url, null, null, 3,10, "utf-8");
		log.info("#getGs() 调用登录验证接口:" + resLoginJson);
		GsLoginResult gsLoginResult = gson.fromJson(resLoginJson, GsLoginResult.class);

		if (gsLoginResult.getCode().equals("112") || gsLoginResult.getCode().equals("113") || gsLoginResult.getCode().equals("116")
				||gsLoginResult.getCode().equals("1")
				) {
			  request.setAttribute("message", gsLoginResult.getMessage());
			  return "/buyer/GJJResult";
		}
		
		
		if (gsLoginResult.getCode().equals("100")) {
			
			boolean flag=true;
			 while (flag) {
				 Thread.sleep(3000);
				 String gs_login2_url = gs_url + "wxyj.unify.acquire/v3?partner_code="+ partner_code + "&partner_key=" + partner_key + "&task_id="+ gsCreateEntity.getTask_id()+ "&task_stage=INIT&request_type=query&login_type="+ gsFactorEntity.getData().get(0).getValue() + "&user_name="+ gsRequest.getUserName() + "&user_pass="+ gsRequest.getUserPass();
					String resLogin2Json = HttpUtils.doPostx(gs_login2_url, null, null, 3,10, "utf-8");
					log.info("#getGs() 调用登录验证轮询接口:" + resLogin2Json);
					GsCode gsCode = gson.fromJson(resLogin2Json, GsCode.class);
					
					if (gsCode.getCode().equals("112") || gsCode.getCode().equals("113") || gsCode.getCode().equals("116")
							||gsCode.getCode().equals("1") ||gsCode.getCode().equals("201") ||gsCode.getCode().equals("2006") 
							) {
						  request.setAttribute("message", gsCode.getMessage());
						  return "/buyer/GJJResult";
					}
					
					if (gsCode.getCode().equals("101")) {
						SHE_BAOCodeEntity sHE_BAOCodeEntity=gson.fromJson(resLogin2Json, SHE_BAOCodeEntity.class);
						String imgName=Base64Utils.GenerateImage(sHE_BAOCodeEntity.getData().getAuth_code());
						String getImg_url = PropertiesUtils.getProperty("getImg_url");
						request.setAttribute("imgUrl", getImg_url+imgName+".jpg");
						request.setAttribute("taskId", sHE_BAOCodeEntity.getTask_id());
						request.setAttribute("taskStage", sHE_BAOCodeEntity.getData().getNext_stage());
						request.setAttribute("loginType", gsFactorEntity.getData().get(0).getValue());
						return "/buyer/SHE_BAOcode";
					}
					
					if (gsCode.getCode().equals("2007")) {
						//调用查询结果接口
							String gs_result_url = gs_url + "task.unify.query/v3?partner_code="+ partner_code + "&partner_key=" + partner_key + "&task_id="+ gsCode.getTask_id();
							String resResultJson = HttpUtils.doPostx(gs_result_url, null, null, 3,10, "utf-8");
							log.info("#getGs() 调用查询结果接口:" + resResultJson);
							if (resResultJson.contains("SHE_BAO")) {
								SHE_BAOResultEntity sHE_BAOResultEntity=gson.fromJson(resResultJson, SHE_BAOResultEntity.class);
								 request.setAttribute("sheResultList", sHE_BAOResultEntity.getData());
								 setSource(zxExternalData.getId(), resResultJson,PropertiesUtils.getProperty("SHE_BAO_type"));
									//社保扣款
								 verifyService.debit(request, "4");
								 return "/buyer/GJJResult";
							}
							
							GsResultEntity gsResultEntity = gson.fromJson(resResultJson,GsResultEntity.class);
							 //最后结果入库处理
							 setSource(zxExternalData.getId(), resResultJson,PropertiesUtils.getProperty("GJJ_type"));
							 request.setAttribute("gjjResultList", gsResultEntity.getData().getTask_data().getBill_record());
							//公积金扣款
							verifyService.debit(request, "3");
							return "/buyer/GJJResult";
						
					}
			 }
		}
		
		return "/buyer/GJJResult";
		
		} catch (Exception e) {
			
			  request.setAttribute("message", "服务器忙请稍后重试！");
			return "/buyer/GJJResult";
		}
	}
	
	
	@IgnoreAuth
	@RequestMapping(value = "getGsShe", produces = "application/json;charset=utf-8")
	public String getGsShe(HttpServletRequest request, GsRequest gsRequest,HttpServletResponse response)
			throws Exception {
		Gson gson=new Gson();
		
		try {
		ZxExternalData zxExternalData=null;
		if (request.getSession().getAttribute("USER_SCORE")!=null) {
			 zxExternalData=(ZxExternalData) request.getSession().getAttribute("USER_SCORE");
			
			log.info("#getGs() 当前用户:" + gson.toJson(zxExternalData));
		}else{
			 PrintWriter out = response.getWriter();  
		        out.println("<html>");      
		        out.println("<script>");      
		        out.println("window.open ('"+request.getContextPath()+"/index','_top')");      
		        out.println("</script>");      
		        out.println("</html>");    
			return null;
		}
		
		String gs_url = PropertiesUtils.getProperty("ssmh_url");
		String partner_code = PropertiesUtils.getProperty("partner_code");
		String partner_key = PropertiesUtils.getProperty("partner_key");
		
		Map<String, String> data = new HashMap<String, String>();
		data.put("partner_code", partner_code);
		data.put("partner_key", partner_key);
		data.put("task_id", gsRequest.getTaskId());
		data.put("auth_code", gsRequest.getCode());
		data.put("task_stage", gsRequest.getTaskStage());
		data.put("request_type", "submit");
		
		String gs_login_url = gs_url + "wxyj.unify.acquire/v3";
		HttpRequest httpRequest = HttpRequest.post(gs_login_url).form(data);
		
		if (httpRequest.ok()) {
		String	resCreateJson = httpRequest.body();
		log.info("#getGs() 调用登陆验证后续接口返回信息：{}" + resCreateJson);
		GsLoginResult gsLoginResult=gson.fromJson(resCreateJson, GsLoginResult.class);
		
		
		if (gsLoginResult.getCode().equals("100")) {
			
			boolean flag=true;
			 while (flag) {
				 Thread.sleep(3000);
				 String gs_login2_url = gs_url + "wxyj.unify.acquire/v3?partner_code="+ partner_code + "&partner_key=" + partner_key + "&task_id="+ gsLoginResult.getTask_id()+ "&task_stage=INIT&request_type=query&login_type="+ gsRequest.getLoginType() + "&user_name="+ gsRequest.getUserName() + "&user_pass="+ gsRequest.getUserPass();
					String resLogin2Json = HttpUtils.doPostx(gs_login2_url, null, null, 3,10, "utf-8");
					log.info("#getGs() 调用登录验证轮询接口:" + resLogin2Json);
					GsCode gsCode = gson.fromJson(resLogin2Json, GsCode.class);
					
					if (gsCode.getCode().equals("112") || gsCode.getCode().equals("113") || gsCode.getCode().equals("116")
							||gsCode.getCode().equals("1") ||gsCode.getCode().equals("201") ||gsCode.getCode().equals("2006") 
							) {
						  request.setAttribute("message", gsCode.getMessage());
						  return "/buyer/GJJResult";
					}
					
					if (gsCode.getCode().equals("101")) {
						SHE_BAOCodeEntity sHE_BAOCodeEntity=gson.fromJson(resLogin2Json, SHE_BAOCodeEntity.class);
						String imgName=Base64Utils.GenerateImage(sHE_BAOCodeEntity.getData().getAuth_code());
						String getImg_url = PropertiesUtils.getProperty("getImg_url");
						request.setAttribute("imgUrl", getImg_url+imgName+".jpg");
						request.setAttribute("taskId", sHE_BAOCodeEntity.getTask_id());
						request.setAttribute("taskStage", sHE_BAOCodeEntity.getData().getNext_stage());
						return "/buyer/SHE_BAOcode";
					}
					
					if (gsCode.getCode().equals("2007")) {
						//调用查询结果接口
							String gs_result_url = gs_url + "task.unify.query/v3?partner_code="+ partner_code + "&partner_key=" + partner_key + "&task_id="+ gsCode.getTask_id();
							String resResultJson = HttpUtils.doPostx(gs_result_url, null, null, 3,10, "utf-8");
							log.info("#getGs() 调用查询结果接口:" + resResultJson);
							if (resResultJson.contains("SHE_BAO")) {
								SHE_BAOResultEntity sHE_BAOResultEntity=gson.fromJson(resResultJson, SHE_BAOResultEntity.class);
								 request.setAttribute("sheResultList", sHE_BAOResultEntity.getData());
								 setSource(zxExternalData.getId(), resResultJson,PropertiesUtils.getProperty("SHE_BAO_type"));
								//社保扣款
								verifyService.debit(request, "4");
								 return "/buyer/GJJResult";
							}
							
							GsResultEntity gsResultEntity = gson.fromJson(resResultJson,GsResultEntity.class);
							 //最后结果入库处理
							 setSource(zxExternalData.getId(), resResultJson,PropertiesUtils.getProperty("GJJ_type"));
							 request.setAttribute("gjjResultList", gsResultEntity.getData().getTask_data().getBill_record());
							//公积金扣款
							verifyService.debit(request, "3");
							return "/buyer/GJJResult";
						
					}
					
			 }
		}
		
		
		}
		return "/buyer/GJJResult";
		
		} catch (Exception e) {
			  request.setAttribute("message", "服务器忙请稍后重试！");
				return "/buyer/GJJResult";
		}
	}


	public void setSource(String externalId,String json,String type){
		Timestamp now = new Timestamp(System.currentTimeMillis());
		
		ZxExternalSource zxExternalSource = new ZxExternalSource();
		zxExternalSource.setId(Sequence.nextId());
		zxExternalSource.setType(type); 
		zxExternalSource.setVersion("v3");
		zxExternalSource.setExternalId(externalId);
		zxExternalSource.setDataSource(json);
		zxExternalSource.setIntertype(Integer.valueOf(3));
		zxExternalSource.setCreateTime(now);
		verifyService.saveSource(zxExternalSource);
	}

	public static void main(String[] args) throws UnsupportedEncodingException {

	}

}
